import { createRouter, createWebHistory } from "vue-router";
import { store } from '@/tools/store';

// 对路由统一管理
const routes = [
    // 登录路由
    {
        path: '/',
        name: 'Login',
        component: () => import('@/views/Login.vue')
    },
    // 首页路由
    {
        path: '/index',
        component: () => import('@/views/Index.vue')
    },
    // 个人信息路由
    {
        path: '/person/:name',
        component: () => import('@/views/Person.vue')
    },
    // 爱心报表路由
    {
        path: '/points',
        component: () => import('@/views/Points.vue')
    },
    // 认领活动中活动列表
    {
        path: '/activity/:name?',
        component: () => import('@/views/Activities.vue'),
        children: [
            {
                path: 'detail/:id',
                component: () => import('@/views/Detail.vue')
            }
        ]
    },
    // 活动详情路由
    {
        path: '/detail/:id',
        component: () => import('@/views/Detail.vue')
    },
    // 我的报名路由
    {
        path: '/myjoin',
        component: () => import('@/views/MyJoin.vue')
    },
    // 服务记录上传路由
    {
        path: '/server',
        component: () => import('@/views/Server.vue')
    },
    // 我的服务路由
    {
        path: '/myserver',
        component: () => import('@/views/MyServer.vue')
    },
    //我的服务中的服务详情页面
    {
        path: '/serverdetail/:id',
        component: () => import('@/views/ServerDetail.vue')
    },
    // 注册路由
    {
        path: '/register',
        component: () => import('@/views/Register.vue')
    }

]

export var url = 'http://localhost:5000'

export var router = new createRouter({
    history: createWebHistory(),
    routes
})

// 全局路由守卫 待解决刷新页面之后用户丢失的bug 建议使用另一个库
router.beforeEach((to, from, next) => {
    // 获取认证状态
    // const isAuthenticated = store.state.isAuthenticated
    // 用户认证状态
    const isUserStatus = localStorage.getItem('userName')
    // 如果访问的不是登录页或注册页，且未登录
    if (to.path !== '/' && to.path !== '/register' && !isUserStatus) {
        next({ name: 'Login' }) // 跳转到登录页
    } else {
        next() // 允许访问
    }
})

